package exam.security;

import cn.hutool.core.util.StrUtil;
import exam.bean.UserInfo;
import exam.dao.GroupAndMenuInfoDao;
import exam.service.IGroupAndMenuInfoService;
import exam.service.IUserInfoService;
import exam.service.UserGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    IUserInfoService userInfoService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Autowired
    UserGroupService userGroupService;

    @Autowired
    IGroupAndMenuInfoService groupAndMenuInfoService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("name",s);
        UserInfo userInfo = userInfoService.selectInfoSingle(queryMap);

//        System.out.println("user:"+userInfo);
//        System.out.println(bCryptPasswordEncoder.encode("admin"));

        if(userInfo == null || StrUtil.isBlankOrUndefined(userInfo.getPassword())){
            throw new UsernameNotFoundException("用户名或密码不正确");
        }

        return new AccountUser(userInfo.getId(),userInfo.getName(),userInfo.getPassword(),getUserAuthority(userInfo));
    }


    /**
     * 获取用户权限信息（角色、菜单权限）
     * @param userInfo    用户id
     * @return
     */
    public List<GrantedAuthority> getUserAuthority(UserInfo userInfo){

//        System.out.println("获取权限列表");
        //获取权限列表
        String permStr = groupAndMenuInfoService.getPermissionMenu(userInfo);

        return AuthorityUtils.commaSeparatedStringToAuthorityList(permStr);
    }
}
